export const useTts = defineStore('tts', () => {
  const text = ref('')
  // 设置tts文本
  const setText = (val: string) => {
    text.value = val
  }

  const ttsVisible = ref(false)
  // 设置tts播放按钮是否可见
  const setTtsVisible = (val: boolean) => {
    ttsVisible.value = val
  }

  return {
    text,
    setText,
    ttsVisible,
    setTtsVisible,
  }
})
// 从html中提取文本
export function getTextFromHtml(html: string) {
  const parser = new DOMParser()
  const doc = parser.parseFromString(html, 'text/html')
  const text = doc.body.textContent || ''
  return text
}

/**
 * 输入一串html字符串，返回一个数组，数组中每一项是以chunkSize个字符为单位分割的html字符，分割时不破坏html标签，
 * @param htmlString
 * @param chunkSize
 * @returns
 */
export function splitHtmlString(htmlString, chunkSize = 500) {
  const parser = new DOMParser()
  const doc = parser.parseFromString(htmlString, 'text/html')
  const body = doc.body
  const chunks = []
  let currentChunk = ''

  function addText(text) {
    if (currentChunk.length + text.length > chunkSize) {
      const remainingSpace = chunkSize - currentChunk.length
      chunks.push(currentChunk + text.slice(0, remainingSpace))
      currentChunk = text.slice(remainingSpace)
    }
    else {
      currentChunk += text
    }
  }

  function traverseNode(node) {
    if (node.nodeType === Node.TEXT_NODE) {
      addText(node.nodeValue)
    }
    else if (node.nodeType === Node.ELEMENT_NODE) {
      currentChunk += `<${node.tagName.toLowerCase()}`
      const attrs = node.attributes
      for (let i = 0; i < attrs.length; i++) {
        currentChunk += ` ${attrs[i].name}="${attrs[i].value}"`
      }
      currentChunk += '>'
      for (const child of node.childNodes) {
        traverseNode(child)
      }
      currentChunk += `</${node.tagName.toLowerCase()}>`
    }
  }

  traverseNode(body)

  if (currentChunk.length > 0) {
    chunks.push(currentChunk)
  }

  return chunks
}
